重構於程式世界代表的是在不變動既有邏輯下去優化改寫程式碼
藉此達到覆用性佳或者提升可讀性甚至性能的一段過程
目前Home.js下Produce清單是直接寫在此的
在此我們可將此段抽離出一個ProductList元件增加程式碼可讀性與提升維護性
第一階段.先重新抽離封裝ProductList
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export class Home extends Component {
static displayName = Home.name;
constructor(props) {
super(props);
this.state = {
products: [
{ title: "some product", description: "interesting", id: 1 },
{ title: "another product", description: "more", id: 2 }
]
};
}
render() {
return (
<div className="row">
{this.state.products.map(product =>
<div key={product.id} className="col-4">
<div className="card product-card">
<div className="card-body">
<h5 className="card-title">{product.title}</h5>
<p className="card-text">{product.description}</p>
<Link to={`/product/${product.id}`}>Detail</Link>
</div>
</div>
</div>
)
}
</div>
);
}
}
新增一個js元件檔命名為ProductList.js
~\ClientApp\src\components\ProductList.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
export default class ProductList extends Component {
constructor(props) {
super(props);
this.state = {
products: [
{ title: "some product", description: "interesting", id: 1 },
{ title: "another product", description: "more", id: 2 }
]
};
}
render() {
return (
<div className="row">
{this.state.products.map(product =>
<div key={product.id} className="col-4">
<div className="card product-card">
<div className="card-body">
<h5 className="card-title">{product.title}</h5>
<p className="card-text">{product.description}</p>
<Link to={`/product/${product.id}`}>View</Link>
</div>
</div>
</div>
)}
</div>
);
}
}
回到Home.js
去調整
import React, { Component } from 'react';
import ProductList from './ProductList';
export class Home extends Component {
static displayName = Home.name;
render() {
return <ProductList />;
}
}
第二階段.針對產品清單在進一步抽離ProductCard
新增一個function component(stateless) ProductCard
~\ClientApp\src\components\ProductCard.js
import React from 'react';
import { Link } from 'react-router-dom';
export default function ProductCard(props) {
return <div className="card product-card">
<div className="card-body">
<h5 className="card-title">{props.product.title}</h5>
<p className="card-text">{props.product.description}</p>
<Link to={`/product/${props.product.id}`}>View</Link>
</div>
</div>
}
外部抽離後進行ProductCard引入
~\ClientApp\src\components\ProductList.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import ProductCard from './ProductCard';
export default class ProductList extends Component {
constructor(props) {
super(props);
this.state = {
products: [
{ title: "some product", description: "interesting", id: 1 },
{ title: "another product", description: "more", id: 2 }
]
};
}
render() {
return (
<div className="row">
{this.state.products.map(product =>
<div key={product.id} className="col-4">
<ProductCard product={product} />
</div>
)}
</div>
);
}
}
如此就能將元件一層層給抽離使可讀性提升,關注點分離
提升重複運用性